package com.tanhua.server.service;

import com.tanhua.commons.pojo.IMessage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLocationDTO;
import com.tanhua.domain.vo.NearUserVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryVO;
import com.tanhua.domain.vo.RecommendUserVO;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Service
public class TanhuaService {
    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserLocationApi userLocationApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private UserLikeApi userLikeApi;

    public ResponseEntity todayBest() {
        long userId = UserHolder.getUser().getId();
        RecommendUser recommendUser = recommendUserApi.findMaxScoreUser(userId);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L);
            recommendUser.setScore(95D);

        }
        Long id = recommendUser.getUserId();
        UserInfo info = userInfoApi.findById(id);
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(info, vo);
        vo.setFateValue(recommendUser.getScore().intValue());
        if (info.getTags() != null) {
            vo.setTags(info.getTags().split(","));
        }
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity recommendation(RecommendUserQueryVO queryVO) {
        //1. 获取当前用户
        User user = UserHolder.getUser();

        //2. 查询给userId推荐的好友 分页信息对象
        PageResult pageResult = recommendUserApi.findRecommendByUser(user.getId(), queryVO.getPage(), queryVO.getPagesize());

        //3. 如果没有查询到，就设置默认值
        List<RecommendUser> items = pageResult.getItems();
        if (items == null || items.size() == 0) {
            items = new ArrayList<>();

            Long[] ids = new Long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L};
            for (Long id : ids) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(id);
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(100D - id);

                items.add(recommendUser);
            }
            pageResult.setCounts(10);
            pageResult.setPages(1);
        }

        //4. 转换成RecommendUserVO列表
        List<RecommendUserVO> voList = new ArrayList<>();
        for (RecommendUser recommendUser : items) {
            // 查询推荐用户的UserInfo
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

            // 转换成RecommendUserVO
            RecommendUserVO vo = new RecommendUserVO();
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }

            // 设置缘分值
            vo.setFateValue(recommendUser.getScore().intValue());

            // 存储到voList里
            voList.add(vo);
        }
        pageResult.setItems(voList);

        //5. 构造返回值
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity findPersonalInfo(Long userId) {
        //查找用户详情
        UserInfo userInfo = userInfoApi.findById(userId);
        //获得好感值
        Integer score = recommendUserApi.findRecommendScore(UserHolder.getUser().getId(), userId);
        //封装到返回值vo
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo,vo);
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        vo.setFateValue(score == null ? 95 : score);

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findStrangerQuestion(Long userId) {

       //查询陌生人问题 并返回
        Question question = questionApi.findByUserId(userId);
        if (question != null) {
            return ResponseEntity.ok(question.getTxt());

        }
        return ResponseEntity.ok("你喜欢我吗");
    }

    public ResponseEntity replyStrangerQuestion(Long targetUserId, String reply) {
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUser().getId());
        Question question = questionApi.findByUserId(targetUserId);

        IMessage message = new IMessage();
        message.setUserId(userInfo.getId().toString());
        message.setNickname(userInfo.getNickname());
        message.setStrangerQuestion(question == null ? "你喜欢起舞吗?" : question.getTxt());
        message.setReply(reply);
        huanXinTemplate.sendMessage(targetUserId.toString(), message);
        return ResponseEntity.ok(null);
    }


    public ResponseEntity searchNear(String gender, Integer distance) {
        //1. 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //2. 调用API，搜索附近的人
        List<UserLocationDTO> locationDTOList = userLocationApi.searchNear(userId, distance);
        //3. 转换成VO，并排除性别不符合的人
        List<NearUserVO> voList = new ArrayList<>();
        for (UserLocationDTO userLocation : locationDTOList) {
            //排除自己
            if (userId.intValue() == userLocation.getUserId()) {
                continue;
            }

            //查找附近的人的详细信息
            UserInfo userInfo = userInfoApi.findById(userLocation.getUserId());
            //排除性别不符合的人
            if (!gender.equals(userInfo.getGender())) {
                continue;
            }

            NearUserVO vo = new NearUserVO();
            vo.setUserId(userInfo.getId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());
            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }
    /**
     * 探花推荐
     * @return
     */
    public ResponseEntity cards() {
        //1. 获取当前用户id
        Long userId = UserHolder.getUser().getId();

        //2. 查询探花推荐
        List<RecommendUser> list = recommendUserApi.findRecommendList(userId);

        //3. 封装返回信息
        List<RecommendUserVO> voList = new ArrayList<>();
        for (RecommendUser recommendUser : list) {
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            RecommendUserVO vo = new RecommendUserVO();
            BeanUtils.copyProperties(userInfo,vo);
            vo.setTags(userInfo.getTags().split(","));
            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }

    /**
     * 探花-喜欢
     * @param loveId
     * @return
     */
    public ResponseEntity tanhuaLove(Long loveId) {
        Long userId = UserHolder.getUser().getId();
        userLikeApi.tanhuaLove(loveId, userId);
        return null;
    }

    /**
     * 探花-不喜欢
     * @param unLoveId
     * @return
     */
    public ResponseEntity tanhuaUnLove(Long unLoveId) {
        Long userId = UserHolder.getUser().getId();
        userLikeApi.tanhuaUnLove(unLoveId, userId);
        return null;
    }
}
